﻿using System;
using System.Web.Mvc;
using Lapkin.Attributes;
using Lapkin.Models.DataModels;
using Lapkin.Models.Repositories;

namespace Lapkin.Areas.Admin.Controllers
{
    [Authorize(Roles = "Admin")]
    public class CategoryController : Controller
    {
        private readonly SqlRepository _repository = new SqlRepository();

        public ActionResult Index()
        {
            ViewBag.Categories = _repository.CategoryRepository.GetListCategory();
            return View(new Category());
        }

        [HttpPost, IsAjax]
        public JsonResult MoveCategory(Guid id, Guid? destination)
        {
            _repository.CategoryRepository.MoveCategory(id, destination);
            return Json(new {Result = "Ok"});
        }
        
        [HttpGet]
        public ActionResult AddCategory()
        {
            return View(new Category());
        }
        [HttpPost]
        public ActionResult AddCategory(Category category)
        {
            Category createdCategory = null;
            if (ModelState.IsValid)
            {
                createdCategory = _repository.CategoryRepository.CreateCategory(c =>
                {
                    c.Name = category.Name;
                    c.Alias = category.Alias;
                }, null);
            }
            return createdCategory != null
                       ? (ActionResult) RedirectToAction("Index")
                       : View(category);
        }

        [HttpPost, IsAjax]
        public PartialViewResult EditCategory(Category category)
        {
            bool resultStatus = true;
            if (!ModelState.IsValid)
            {
                resultStatus = false;
            }
            else
            {
                if (!_repository.CategoryRepository.UpdateCategory(category))
                {
                    resultStatus = false;
                }
            }
            ViewBag.ModelStatus = resultStatus;
            return PartialView("_CategoryForm", category); ;
        }

        [HttpPost, IsAjax]
        public JsonResult RemoveCategory(Guid id)
        {
            bool resultStatus = !_repository.CategoryRepository.RemoveCategory(id);
            return resultStatus
                       ? Json(new {Result = "OK"})
                       : Json(new {Result = "ERROR"});
        }
    }
}
